package com.ruoyi.kis.controller;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult_KIS;
import com.ruoyi.kis.Vars.Constants;
import com.ruoyi.kis.annotaion.BasicAuthCheck;
import com.ruoyi.kis.domain.MaterialRequisiteF;
import com.ruoyi.kis.service.IKisService;
import com.ruoyi.kis.util.HttpSendWmsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @Author: zhanglm
 * @CreateDate: 2025-02-26 15:02
 * @FullNameClass: com.ruoyi.kis.controller.KisStoresRequisitions
 * @Description: 领料单、领料单反馈
 */
@RestController
@RequestMapping("/kislld")
@Component("kislld")
@Api("kis领料单接口")
public class KisLldController extends BaseController {

    @Autowired
    private IKisService kisService;
    @Autowired
    private HttpSendWmsUtil httpSendWmsUtil;
    private static final Logger LOGGER = LoggerFactory.getLogger(KisLldController.class);


    /**
     * 领料单
     * materialRequisite
     * ERP > WMS
     * @return json
     */
    @ApiOperation("领料单")
    @RequestMapping("/lld")
    public AjaxResult_KIS lingliaodan(){
        List<MaterialRequisiteF> materialRequisiteList = kisService.queryMaterialRequisiteF();//查询领料单用false
        String s  = "";
        if (materialRequisiteList != null && materialRequisiteList.size() > 0){
            s = JSONUtil.parse(materialRequisiteList.get(0)).toString();
            try {
//                String msg = HttpUtil.post(Constants.MATERIAL_REQUISITE_URL,s);
                String msg = HttpSendWmsUtil.sendWms(Constants.MATERIAL_REQUISITE_URL,s);
                LOGGER.info("领料单ERP >> WMS传送的JSON:"+s);
                JSONObject entries = JSONUtil.parseObj(msg);
                String msgcode = entries.get("msgcode").toString();
                String kisFlag;
                if (msgcode.equals("0")){
                    kisFlag = Constants.ZHIKU.KISFLAG_SUCCESS;
                }else {
                    kisFlag = Constants.ZHIKU.KISFLAG_FAILURE;
                }
                int countUpdate = kisService.updateKisICStockBillFlag(materialRequisiteList.get(0).getFInterID(),kisFlag);
                LOGGER.info("领料单 ERP >> WMS,单据号：{},单据状态更新状态：{},条数：{},反馈：{}",materialRequisiteList.get(0).getFBillNo(),kisFlag,countUpdate,msg);
            }catch (HttpException e){
                LOGGER.error("领料单反馈失败" + e.getMessage());
            }
        }
        return AjaxResult_KIS.success("OK","");

    }

    /**
     * 领料单反馈
     * 单据类型：2
     */
    @ApiOperation("领料单反馈")
    @RequestMapping("/lldfeedback")
    public AjaxResult_KIS lldFeedback(@RequestBody MaterialRequisiteF materialRequisiteF){
        Map map = kisService.updateLldFeedBack(materialRequisiteF);
        LOGGER.info("领料单反馈保存表体数量："+map);
        if (map.get("MSGCODE").toString().equals("0")){
            JSON parse = JSONUtil.parse(materialRequisiteF);
            String s =  parse.toString();
            LOGGER.info("领料单反馈保存数据："+s);
            return AjaxResult_KIS.success("success","领料单反馈保存成功");
        }else {
            LOGGER.error("领料单反馈保存表体数量为0");
            return AjaxResult_KIS.success("error",map.get("MSG").toString());

        }

    }
    /**
     * 红领料单_下发
     * materialRequisite
     * ERP > WMS
     * @return json
     */
    @ApiOperation("红领料单_下发")
    @RequestMapping("/lldReverse")
    public AjaxResult_KIS lldReverse(){
//        Date orderTime = kisService.queryCurrentTime(Constants.MATERIAL_REQUISITE);
        List<MaterialRequisiteF> materialRequisiteList = kisService.queryMaterialRequisiteF_NX();//查询领料单用false
        String s  = "";
        if (materialRequisiteList != null && materialRequisiteList.size() > 0){
            s = JSONUtil.parse(materialRequisiteList.get(0)).toString();
            try {
                LOGGER.info("红领料单_下发 >> WMS传送的JSON:"+s);
                String msg = httpSendWmsUtil.sendWms(Constants.SCLLD_RED_URL,s);
                JSONObject entries = JSONUtil.parseObj(msg);
                String msgcode = entries.get("msgcode").toString();
                String kisFlag;
                if (msgcode.equals(Constants.ZHIKU.MSGCODE_SUCCESS)){
                    kisFlag = Constants.ZHIKU.KISFLAG_SUCCESS;
                }else {
                    kisFlag = Constants.ZHIKU.KISFLAG_FAILURE;
                }
                int countUpdate = kisService.updateKisICStockBillFlag(materialRequisiteList.get(0).getFInterID(),kisFlag);
                LOGGER.info("红领料单_下发 ERP >> WMS,单据号：{},单据状态kisFlag更新为{},条数：{},反馈：{}",materialRequisiteList.get(0).getFBillNo(),kisFlag,countUpdate,msg);
            }catch (HttpException e){
                LOGGER.error("红领料单_下发反馈失败" + e.getMessage());
            }
        }
        return AjaxResult_KIS.success("OK","");

    }


    /**
     * 红领料单_反馈
     * 单据类型：2
     */
    @ApiOperation("领料单逆向_反馈")
    @RequestMapping("/lldReverseFeedback")
    @BasicAuthCheck
    public AjaxResult_KIS lldReverseFeedback(@RequestBody MaterialRequisiteF materialRequisiteF){
        LOGGER.info("红色领料单WMS-ERP:" + materialRequisiteF);
        Map map = kisService.updateLldReverseFeedBack(materialRequisiteF);
        LOGGER.info("领料单逆向_反馈保存表体数量："+map);
        if (map.get("MSGCODE").toString().equals("0")){
            JSON parse = JSONUtil.parse(materialRequisiteF);
            String s =  parse.toString();
            LOGGER.info("领料单逆向_反馈保存数据："+s);
            return AjaxResult_KIS.success("success","红领料单反馈保存成功");
        }else {
            LOGGER.error("红领料单反馈保存表体数量为0");
            return AjaxResult_KIS.error("error",map.get("MSG").toString());

        }

    }


    @ApiOperation("离线领料单反馈")
    @RequestMapping("/lldFeedbackReverse")
    @BasicAuthCheck
    public AjaxResult_KIS lldFeedbackReverse(@RequestBody MaterialRequisiteF materialRequisiteF){
        Map map = kisService.saveLldFeedBackReverse(materialRequisiteF);
        LOGGER.info("领料单反馈保存表体数量："+map);
        if (map.get("MSGCODE").toString().equals("0")){
            JSON parse = JSONUtil.parse(materialRequisiteF);
            String s =  parse.toString();
            LOGGER.info("领料单逆向_反馈（红）："+s);
            return AjaxResult_KIS.success("success","领料单逆向_反馈（红）保存成功");
        }else {
            LOGGER.error("领料单逆向_反馈（红）保存表体数量为0");
            return AjaxResult_KIS.success("error",map.get("MSG").toString());

        }

    }
}
